/**
 * 导出服务 - 支持多种格式的对话导出
 */
class ExportService {
  constructor() {
    this.supportedFormats = ['json', 'markdown', 'html', 'pdf']
  }

  /**
   * 导出对话到指定格式
   * @param {Array} messages - 消息数组
   * @param {string} format - 导出格式 (json, markdown, html, pdf)
   * @param {Object} options - 导出选项
   */
  async exportChat(messages, format = 'json', options = {}) {
    if (!this.supportedFormats.includes(format)) {
      throw new Error(`不支持的导出格式: ${format}`)
    }

    const timestamp = new Date().toISOString().split('T')[0]
    const filename = `chat-export-${timestamp}`

    switch (format) {
      case 'json':
        return this.exportToJSON(messages, filename, options)
      case 'markdown':
        return this.exportToMarkdown(messages, filename, options)
      case 'html':
        return this.exportToHTML(messages, filename, options)
      case 'pdf':
        return this.exportToPDF(messages, filename, options)
      default:
        throw new Error(`未实现的导出格式: ${format}`)
    }
  }

  /**
   * 导出为JSON格式
   */
  exportToJSON(messages, filename, options) {
    const chatData = {
      messages: messages,
      timestamp: new Date().toISOString(),
      version: '1.0',
      exportFormat: 'json'
    }

    const dataStr = JSON.stringify(chatData, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    this.downloadFile(dataBlob, `${filename}.json`)
  }

  /**
   * 导出为Markdown格式
   */
  exportToMarkdown(messages, filename, options) {
    let markdown = `# AI对话记录\n\n`
    markdown += `**导出时间**: ${new Date().toLocaleString('zh-CN')}\n`
    markdown += `**消息数量**: ${messages.length}\n\n`
    markdown += `---\n\n`

    messages.forEach((message, index) => {
      const timestamp = new Date(message.timestamp).toLocaleString('zh-CN')
      const role = message.role === 'user' ? '👤 用户' : '🤖 AI助手'
      
      markdown += `## ${role} - ${timestamp}\n\n`
      markdown += `${message.content}\n\n`
      
      if (index < messages.length - 1) {
        markdown += `---\n\n`
      }
    })

    const dataBlob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' })
    this.downloadFile(dataBlob, `${filename}.md`)
  }

  /**
   * 导出为HTML格式
   */
  exportToHTML(messages, filename, options) {
    const html = this.generateHTML(messages, options)
    const dataBlob = new Blob([html], { type: 'text/html;charset=utf-8' })
    this.downloadFile(dataBlob, `${filename}.html`)
  }

  /**
   * 导出为PDF格式
   */
  async exportToPDF(messages, filename, options) {
    try {
      // 首先尝试HTML转PDF的方式
      await this.exportHTMLToPDF(messages, filename, options)
    } catch (error) {
      console.error('HTML转PDF失败，尝试备用方案:', error)
      try {
        // 备用方案：使用简单的文本PDF
        await this.exportSimplePDF(messages, filename, options)
      } catch (fallbackError) {
        console.error('备用PDF导出也失败:', fallbackError)
        // 最后回退到HTML导出
        this.exportToHTML(messages, filename, options)
      }
    }
  }

  /**
   * 简单的PDF导出方案（备用）
   */
  async exportSimplePDF(messages, filename, options) {
    const { jsPDF } = await import('jspdf')
    
    const pdf = new jsPDF('p', 'mm', 'a4')
    const pageWidth = pdf.internal.pageSize.getWidth()
    const pageHeight = pdf.internal.pageSize.getHeight()
    const margin = 20
    const maxWidth = pageWidth - 2 * margin
    
    let yPosition = margin
    const lineHeight = 7
    const titleHeight = 15

    // 添加标题
    pdf.setFontSize(16)
    pdf.text('AI对话记录', margin, yPosition)
    yPosition += titleHeight

    // 添加导出信息
    pdf.setFontSize(10)
    pdf.text(`导出时间: ${new Date().toLocaleString('zh-CN')}`, margin, yPosition)
    yPosition += lineHeight
    pdf.text(`消息数量: ${messages.length}`, margin, yPosition)
    yPosition += lineHeight * 2

    // 添加消息内容
    pdf.setFontSize(12)
    messages.forEach((message, index) => {
      // 检查是否需要新页面
      if (yPosition > pageHeight - 40) {
        pdf.addPage()
        yPosition = margin
      }

      const timestamp = new Date(message.timestamp).toLocaleString('zh-CN')
      const role = message.role === 'user' ? '用户' : 'AI助手'
      
      // 添加角色和时间戳
      pdf.setFontSize(10)
      pdf.text(`${role} - ${timestamp}`, margin, yPosition)
      yPosition += lineHeight

      // 添加消息内容
      pdf.setFontSize(12)
      const content = message.content.replace(/\n/g, ' ')
      
      // 使用简单的文本分割
      const words = content.split('')
      let currentLine = ''
      
      for (let i = 0; i < words.length; i++) {
        const testLine = currentLine + words[i]
        const textWidth = pdf.getTextWidth(testLine)
        
        if (textWidth > maxWidth && currentLine !== '') {
          if (yPosition > pageHeight - 20) {
            pdf.addPage()
            yPosition = margin
          }
          pdf.text(currentLine, margin, yPosition)
          yPosition += lineHeight
          currentLine = words[i]
        } else {
          currentLine = testLine
        }
      }
      
      // 添加最后一行
      if (currentLine) {
        if (yPosition > pageHeight - 20) {
          pdf.addPage()
          yPosition = margin
        }
        pdf.text(currentLine, margin, yPosition)
        yPosition += lineHeight
      }
      
      yPosition += lineHeight // 消息间间距
    })

    // 下载PDF
    pdf.save(`${filename}.pdf`)
  }

  /**
   * 通过HTML转PDF的方式导出
   */
  async exportHTMLToPDF(messages, filename, options) {
    // 生成HTML内容
    const html = this.generateHTML(messages, { ...options, includeStyles: true })
    
    // 创建临时容器
    const tempContainer = document.createElement('div')
    tempContainer.innerHTML = html
    tempContainer.style.position = 'absolute'
    tempContainer.style.left = '-9999px'
    tempContainer.style.top = '-9999px'
    tempContainer.style.width = '800px'
    tempContainer.style.fontFamily = 'Microsoft YaHei, 微软雅黑, SimSun, 宋体, sans-serif'
    tempContainer.style.fontSize = '14px'
    document.body.appendChild(tempContainer)

    // 等待DOM渲染完成
    await new Promise(resolve => setTimeout(resolve, 200))

    try {
      // 动态导入html2canvas和jsPDF
      const [{ default: html2canvas }, { jsPDF }] = await Promise.all([
        import('html2canvas'),
        import('jspdf')
      ])

      // 将HTML转换为canvas
      const canvas = await html2canvas(tempContainer, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
        width: 800,
        height: tempContainer.scrollHeight,
        logging: false,
        foreignObjectRendering: true
      })

      // 创建PDF
      const imgData = canvas.toDataURL('image/png', 1.0)
      const pdf = new jsPDF('p', 'mm', 'a4')
      
      const imgWidth = 210 // A4宽度
      const pageHeight = 295 // A4高度
      const imgHeight = (canvas.height * imgWidth) / canvas.width
      let heightLeft = imgHeight

      let position = 0

      // 添加图片到PDF
      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
      heightLeft -= pageHeight

      // 如果内容超过一页，添加新页面
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight
        pdf.addPage()
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
        heightLeft -= pageHeight
      }

      // 下载PDF
      pdf.save(`${filename}.pdf`)
    } finally {
      // 清理临时容器
      if (tempContainer.parentNode) {
        document.body.removeChild(tempContainer)
      }
    }
  }


  /**
   * 生成HTML内容
   */
  generateHTML(messages, options = {}) {
    const { includeStyles = true, theme = 'light' } = options
    
    const styles = includeStyles ? `
      <style>
        body {
          font-family: 'Microsoft YaHei', '微软雅黑', 'SimSun', '宋体', 'PingFang SC', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', sans-serif;
          line-height: 1.6;
          color: ${theme === 'dark' ? '#e5e7eb' : '#374151'};
          background-color: ${theme === 'dark' ? '#1f2937' : '#ffffff'};
          max-width: 800px;
          margin: 0 auto;
          padding: 20px;
          font-size: 14px;
        }
        .header {
          border-bottom: 2px solid ${theme === 'dark' ? '#374151' : '#e5e7eb'};
          padding-bottom: 20px;
          margin-bottom: 30px;
        }
        .message {
          margin-bottom: 30px;
          padding: 15px;
          border-radius: 8px;
          border-left: 4px solid;
        }
        .message.user {
          background-color: ${theme === 'dark' ? '#374151' : '#f3f4f6'};
          border-left-color: #3b82f6;
        }
        .message.assistant {
          background-color: ${theme === 'dark' ? '#1f2937' : '#ffffff'};
          border-left-color: #10b981;
          border: 1px solid ${theme === 'dark' ? '#374151' : '#e5e7eb'};
        }
        .message-header {
          font-weight: 600;
          margin-bottom: 10px;
          display: flex;
          align-items: center;
          gap: 8px;
        }
        .message-content {
          white-space: pre-wrap;
          word-wrap: break-word;
        }
        .timestamp {
          font-size: 0.875rem;
          color: ${theme === 'dark' ? '#9ca3af' : '#6b7280'};
        }
        .export-info {
          font-size: 0.875rem;
          color: ${theme === 'dark' ? '#9ca3af' : '#6b7280'};
          margin-bottom: 10px;
        }
      </style>
    ` : ''

    let html = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI对话记录</title>
  ${styles}
</head>
<body>
  <div class="header">
    <h1>AI对话记录</h1>
    <div class="export-info">
      <p>导出时间: ${new Date().toLocaleString('zh-CN')}</p>
      <p>消息数量: ${messages.length}</p>
    </div>
  </div>

  <div class="messages">
`

    messages.forEach(message => {
      const timestamp = new Date(message.timestamp).toLocaleString('zh-CN')
      const role = message.role === 'user' ? 'user' : 'assistant'
      const roleIcon = message.role === 'user' ? '👤' : '🤖'
      const roleText = message.role === 'user' ? '用户' : 'AI助手'
      
      html += `
    <div class="message ${role}">
      <div class="message-header">
        <span>${roleIcon}</span>
        <span>${roleText}</span>
        <span class="timestamp">${timestamp}</span>
      </div>
      <div class="message-content">${this.escapeHtml(message.content)}</div>
    </div>
`
    })

    html += `
  </div>
</body>
</html>`

    return html
  }

  /**
   * HTML转义
   */
  escapeHtml(text) {
    const div = document.createElement('div')
    div.textContent = text
    return div.innerHTML
  }

  /**
   * 下载文件
   */
  downloadFile(blob, filename) {
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = filename
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  /**
   * 获取支持的格式列表
   */
  getSupportedFormats() {
    return [...this.supportedFormats]
  }

  /**
   * 获取格式的显示名称
   */
  getFormatDisplayName(format) {
    const names = {
      json: 'JSON',
      markdown: 'Markdown',
      html: 'HTML',
      pdf: 'PDF'
    }
    return names[format] || format.toUpperCase()
  }
}

export default new ExportService()
